<?php

namespace app\admin\controller;

use app\admin\model\User;
use app\api\controller\Team;
use app\common\controller\Backend;
use app\common\func\Lib;
use app\common\model\PolicyRelation;
use think\Db;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 产品代理申请
 *
 * @icon fa fa-circle-o
 */
class ProductApply extends Backend
{

    /**
     * ProductApply模型对象
     * @var \app\common\model\ProductApply
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\ProductApply;
        $this->view->assign("mainTypeList", $this->model->getMainTypeList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    public function index1()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            if($this->auth->isSuperAdmin()){
                $result = array();
            }else{
                $list = Db::name("product_apply")->alias("a")
                    ->join("user u","a.main_id = u.id","LEFT")
                    ->where(["u.ptype" => 1,"u.pid" => $this->auth->getCompany()->id])
                    ->field("a.id,a.product_ids,a.status,a.create_time,u.nickname,u.mobile")
                    ->paginate();

                $result = array("total" => $list->total(), "rows" => $list->items());
            }

            return json($result);
        }
        return $this->view->fetch();
    }

    public function add()
    {
        if (false === $this->request->isPost()) {
            if($this->auth->getCompany()->pid == 0){
                $productList = \app\common\model\Product::where(["status" => 1])->select();
            }else{
                $productList = Lib::getUserProduct(1,$this->auth->getCompany()->id);
            }
            $this->view->assign("product_list",$productList);
            return $this->view->fetch();
        }
        $productArr = $this->request->post('product/a');

        $result = false;
        Db::startTrans();
        try {
            $arr = [
                "main_type" => 1,
                "main_id" => $this->auth->getCompany()->id,
                "product_ids" => implode(",",$productArr),
            ];
            $result = $this->model->allowField(true)->save($arr);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    public function detail($ids){
        if (false === $this->request->isPost()) {
            $info = Db::name("product_apply")->alias("a")
                ->join("user u","a.main_id = u.id","LEFT")
                ->where(["u.ptype" => 1,"u.pid" => $this->auth->getCompany()->id])
                ->where(["a.id" => $ids])
                ->field("a.id,a.product_ids,a.create_time,u.nickname,u.mobile")
                ->find();

            $info['product'] = Lib::getProductByIds($info['product_ids']);
            if(count($info['product']) > 0){
                foreach ($info['product'] as $key => $val){
                    $val->policy = Lib::getMyPolicyByProduct(1,$this->auth->getCompany()->id,$val->id);
                }
            }

            $this->view->assign("row",$info);
            return $this->view->fetch();
        }

        $params = $this->request->post();

        if(count($params['policy']) == 0){
            $this->error("未进行政策设置");
        }
        $apply = $this->model->get($ids);

        $result = false;
        Db::startTrans();
        try {
            foreach ($params['policy'] as $key => $val){
                if($val['default'] == 1){
                    PolicyRelation::where(["main_type" => $apply->main_type,"main_id" => $apply->main_id,"product_id" => $val['product_id']])->update(["default" => 0]);
                }

                Team::saveProductPolicyRelation($apply->main_id,$val,$apply->main_type);
            }

            //更新主体设置政策状态
            if($apply->main_type == 1){
                $obj = \app\common\model\Company::get($apply->main_id);
            }else{
                $obj = User::get($apply->main_id);
            }
            if($obj->is_setting == 0){
                $obj->is_setting = 1;
                $obj->save();
            }

            //修改申请状态
            $apply->status = 1;
            $result = $apply->save();

            Db::commit();
        } catch (ValidateException|PDOException|\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }

        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            if($this->auth->isSuperAdmin()){
                $result = [];
            }else{
                $list = $this->model->alias("a")
                    ->join("user u","a.main_id = u.id","LEFT")
                    ->where($where)
                    ->where(["u.ptype" => 1,"u.pid" => $this->auth->getCompany()->id])
                    ->order($sort, $order)
                    ->field("a.id,a.product_ids,a.status,a.create_time,u.nickname,u.mobile")
                    ->paginate($limit);

            foreach ($list as $row) {
                $products = Lib::getProductByIds($row->product_ids);
                $arr = [];
                if(count($products) > 0){
                    foreach ($products as $val){
                        $arr[] = "【{$val->name}】";
                    }
                    $row->product = implode(",",$arr);
                }else{
                    $row->product = "暂无";
                }
//                $row->visible(['id','product_ids','create_time']);

            }

                $result = array("total" => $list->total(), "rows" => $list->items());
            }

            return json($result);
        }
        $this->view->assign("is_admin",$this->auth->isSuperAdmin());
        return $this->view->fetch();
    }

    /**
     * 删除
     *
     * @param $ids
     * @return void
     * @throws DbException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public function del($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post("ids");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = $this->model->where($pk, 'in', $ids)->select();

        $count = 0;
        Db::startTrans();
        try {
            foreach ($list as $item) {
                if($item->status == 1){
                    $this->error("已设置默认的不允许删除！");
                }
                $count += $item->delete();
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were deleted'));
    }

}
